package com.huxin.servelt.admin;


import com.alibaba.fastjson.JSON;
import com.huxin.pojo.BookStorage;
import com.huxin.pojo.BooksInfo;
import com.huxin.service.Userservice;
import org.springframework.beans.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Date;

@WebServlet("/admin/addBook")
public class AdminAddBookServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String s = req.getReader().readLine();
        BooksInfo booksInfo = JSON.parseObject(s, BooksInfo.class);

        BookStorage bookStorage = BookStorage.builder()
                .num(booksInfo.getNum())
                .imgpath(booksInfo.getImgpath())
                .press(booksInfo.getPress())
                .author(booksInfo.getAuthor())
                .type(booksInfo.getType())
                .name(booksInfo.getName()).build();

        bookStorage.setStorage_time(new Date(System.currentTimeMillis()));
        booksInfo.setCard("0");
        Userservice userservice = new Userservice();


        //用传进来的bookStorage数据查询该书籍是否存在
        BooksInfo booksInfo1=userservice.findBookByNameAndAuthor(booksInfo);
        if (booksInfo1!=null){//该书籍存在
            bookStorage.setImgpath(booksInfo1.getImgpath());
            bookStorage.setBid(booksInfo1.getBid());
            //只增加书籍数量
            int i=userservice.addBookNumByNameAndAuthor(booksInfo);
            //在书籍入库表中新增记录
            int ii=userservice.addBookStorage(bookStorage);
            if (i==ii&&i==1){
                resp.getWriter().write("1");
            }
        }else{//该书籍不存在
            //新增书籍并记录
            //在书籍表中增加书籍
           userservice.addBooks(booksInfo);
           //根据书名和作者查询书籍
            BooksInfo newBooksInfo=userservice.findBookByNameAndAuthor(booksInfo);
            //再将数据存入 入库表
            bookStorage.setImgpath(newBooksInfo.getImgpath());
            bookStorage.setBid(newBooksInfo.getBid());
            int ii=userservice.addBookStorage(bookStorage);
            if (ii==1){
                resp.getWriter().write("1");
            }

        }
//        System.out.println("`````````````````"+booksInfo1);
        //存在的话就只需要加数量
        //不存在的话就需要新增书籍



//        int i=userservice.addBooks(booksInfo);
//        resp.getWriter().write(String.valueOf(i));
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
